import React, { useEffect, useState } from "react";
import { InfiniteScroll, PullToRefresh, List, Avatar, Image, Dialog, DotLoading } from "antd-mobile";
import { sleep } from "antd-mobile/es/utils/sleep";
import styles from './index.module.less'
import { EyeFill, DeleteOutline } from 'antd-mobile-icons'
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { getChatList, deleteChat, getChatModelList } = $globalServicer('chat')
const { getUserInfo } = $globalServicer('My')
const ChatListItem = ({ tabType = 'conversations' }) => {
  function getNextData() {
    const ret = [];
    for (let i = 0; i < 100; i += 1) {
      ret.push(`${i}`);
    }
    return ret;
  }
  const InfiniteScrollContent = ({ hasMore }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 已到达底部 ---</span>
        )}
      </>
    )
  }
  const customNavigate = $globalNavigate()
  const [data, setData] = useState([]);
  const [chatList, setChatList] = useState([]);
  const [hasMore, setHasMore] = useState(false);
  const [userInfo, setUserInfo] = useState(null)
  const loadMore = async () => {
    const append = await getNextData();
    setData([...data, ...append]);
    setHasMore(append.length > 0);
  };
  const fetchChatList = async () => {
    const res = await getChatList();
    const response = await getChatModelList()
    console.log("===> ~ index.jsx:43 ~ fetchChatList ~ response:", response)
    if (Array.isArray(res)) {
      setChatList(res)
    } else {
      setChatList([])
    }
  }
  const handleDelectChat = async (e, chat) => {
    e.stopPropagation()
    Dialog.confirm({
      content: '是否确认删除该聊天？',
      cancelText:
        <div className={styles.cancelClass}>
          取消
        </div>,
      confirmText: <div className={styles.confirmClass}>确认</div>,
      onConfirm: async () => {
        await deleteChat({ id: chat.id }).then((res) => {
          showSuccessToast('删除成功');
          fetchChatList()
        })
      },
    })
  }
  const handleStartChat = async (chat) => {
    const name = chat.name
    if (chat.chat_id === null) {
      showErrorToast(`聊天系统繁忙，请稍后再试`)
      return
    }
    // if (userInfo?.user?.level_id === 0) {
    //   Dialog.confirm({
    //     content: '您的会员已到期，请续费后继续与AI聊天',
    //     cancelText:
    //       <div className={styles.cancelClass}>
    //         取消
    //       </div>,
    //     onCancel: () => {
    //       customNavigate(`/chatDetail?type=${chat.type}&chatId=${chat.id}&name=${chat.name}`)
    //     },
    //     confirmText: <div className={styles.confirmClass}>购买会员</div>,
    //     onConfirm: () => {
    //       customNavigate('/goods')
    //     },
    //   })
    //   return
    // }
    customNavigate(`/chatDetail?type=${chat.type}&chatId=${chat.id}&name=${name}`)
  }
  useEffect(() => {
    const childReloads = sessionStorage.getItem('childReloads');
    if (childReloads === 'true') {
      // 重置 childReloads 为 false
      sessionStorage.setItem('childReloads', 'false');
    } else {
      const fetchData = async () => {
        setHasMore(true)
        if (typeof window?.getCharacters === 'function') {
          console.log("🚀 ~ useEffect ~ 触发 ~ window?.getCharacters:", window?.getCharacters);
          try {
            await window.getCharacters();
          } catch (error) {
            console.error("获取角色时出错：", error);
          }
        }
        await fetchChatList();
        await getUserInfo().then(res => {
          setUserInfo(res)
        })
        setHasMore(false)
      };
      setTimeout(() => {
        fetchData()
      }, 10);
    }
  }, [tabType]);
  return (
    <div className={styles.chatListItemWrapper}>
      <PullToRefresh
        key={tabType}
        onRefresh={async () => {
          await sleep(1000);
          setData([...getNextData(), ...data]);
        }}
      >
        <div className={styles.item_list}>
          <List>
            {chatList?.map((chat, index) => (
              <List.Item
                key={chat.id}
                prefix={
                  <Image
                    src={chat.cover}
                    style={{ borderRadius: 20 }}
                    fit='cover'
                    width={40}
                    height={40}
                  />
                }
                description={chat.last_message}
                extra={<span onClick={(e) => handleDelectChat(e, chat)}><DeleteOutline /></span>}
                arrowIcon={false}
                onClick={() => {
                  handleStartChat(chat)
                }}
              >
                {
                  chat.type === 1 ? <>{chat.name}</> : <>{chat.name}</>
                }
              </List.Item>
            ))}
          </List>
        </div>
        <InfiniteScroll threshold={20} >
          <InfiniteScrollContent hasMore={hasMore} />
        </InfiniteScroll>
      </PullToRefresh>
    </div>
  );
};

export default ChatListItem;
